const Router = require('koa-router');
const MplCtl= require('../../controllers/matchplayers.js')
const eventCtl= require('../../controllers/events.js')
const router = new Router();
const mongoose = require('mongoose');
const {Schema, model} = mongoose;

/**
 * @swagger
 * tags:
 *   - name: matchplayer
 *     description: Everything about matchplayer
 */

router
/**
 * @swagger
 * paths:
 *   /matchplayers:
 *     get:
 *       tags:
 *         - matchplayer
 *       summary: Return a list of matchplayers
 *       description: ''
 *       produces:
 *         - application/json
 *       responses:
 *         200:
 *           description: OK
 *           schema:
 *             type: array
 *             items:
 *               $ref: '#/definitions/matchplayer'
 */
    .get('/', async (ctx, next)=>{ ctx.body = await MplCtl.list(); })

/**
 * @swagger
 * paths:
 *   /matchplayers:
 *     post:
 *       tags:
 *         - matchplayer
 *       summary: Create a matchplayer
 *       description: ''
 *       parameters:
 *         - in: body
 *           name: "body"
 *           description: ""
 *           required: true
 *           schema:
 *             $ref: "#/definitions/matchplayer"
 *       produces:
 *         - application/json
 *       responses:
 *         200:
 *           description: OK
 */
    .post('/', async (ctx, next)=>{
        const {id} = ctx.params;
        const data = ctx.request.body;
        let  r = await MplCtl.create(data);
        ctx.body = r;
    })
/**
 * @swagger
 * paths:
 *   /matchplayers/{id}:
 *     get:
 *       tags:
 *         - competition
 *       summary: Return a matchplayer
 *       description: ''
 *       parameters:
 *         - in: path
 *           name: id 
 *           description: ""
 *           required: true
 *           type: string
 *       produces:
 *         - application/json
 *       responses:
 *         200:
 *           description: OK
 *           schema:
 *             $ref: '#/definitions/matchplayer'
 */
    .get('/:id', async (ctx, next)=>{
        // Retrieves informations about a given matchplayer
        const {id} = ctx.params;
        const r = await MplCtl.retrieve(id);
        ctx.assert(r !== null, 404, 'Detail not found!');

        ctx.body = r;
    })

/**
 * @swagger
 * paths:
 *   /matchplayers/{id}:
 *     put:
 *       tags:
 *         - competition
 *       summary: Update or create a matchplayer
 *       description: ""
 *       parameters:
 *         - in: path
 *           name: id 
 *           description: ""
 *           required: true
 *           type: string
 *         - in: body
 *           name: body
 *           description: ""
 *           required: true
 *           schema:
 *             $ref: "#/definitions/matchplayer"
 *
 *       produces:
 *         - application/json
 *       responses:
 *         200:
 *           description: OK
 */
    .put('/:id', async (ctx, next)=>{
        const id = ctx.params.id;
        const data = ctx.request.body;
        const r = await MplCtl.upsert(id, data);
        
        ctx.body = r;
    })

/**
 * @swagger
 * paths:
 *   /matchplayers/{cid}:
 *     delete:
 *       tags:
 *         - matchplayer
 *       summary: Delete a matchplayer
 *       description: ""
 *       parameters:
 *         - in: path
 *           name: id 
 *           description: ""
 *           required: true
 *           type: string
 *
 *       produces:
 *         - application/json
 *       responses:
 *         204:
 *           description: No content
 */
    .delete('/:id', async (ctx, next)=>{
        MplCtl.removeById(ctx.params.id);
        ctx.status = 204;
    })
/**
 * @swagger
 * paths:
 *   /competitions/{cid}/seasons:
 *     get:
 *       tags:
 *         - competition
 *       summary: Return the list of seasons of the given competition
 *       description: ""
 *       parameters:
 *         - in: path
 *           name: cid 
 *           description: ""
 *           required: true
 *           type: string
 *
 *       produces:
 *         - application/json
 *       responses:
 *         200:
 *           description: OK
 */
    .get('/:id/seasons', async (ctx, next)=>{
        const {id} = ctx.params;
        ctx.body = "TODO find the list of seasons of competition" + id;
        ctx.throw(500);
    })


    .get('/shuang/:playerid', async (ctx, next)=>{
        const {playerid} = ctx.params;
        const {matchId} = ctx.query;
        //const r = await eventCtl.retrieve(playerid);
        const r = await MplCtl.find({playerId:playerid, matchId});

        console.log(r)
        //let bisai = [];
        var result = [];
        for(let d of r) { result.push(d)}
        //console.log(result)*/
        /**for(let round of r) {
            console.log(round.constructor)
            for(let key of Object.keys(round)) {
                console.log('key:', key)
                //if(Number.isNaN(+key)) { continue; }
                //console.log('in')
                if(round[key] == matchId){
                    //for(let d of round) { bisai.push(d)}
                    bisai.push(round)
                    console.log(bisai)
                }
                else { continue;}
            }
        }
        for(let a of bisai) {
            //console.log(a.constructor)
            for(let key of Object.keys(a)) {
                //console.log('key:', key)
                //if(Number.isNaN(+key)) { continue; }
                //console.log('in')
                if(a[key] == 'Pass'){
                    //for(let d of round) { bisai.push(d)}
                    result.push(a)
                    console.log(result)
                }
                else { continue;}
            }
        }*/
        /**result['1H']=[];result['2H']=[];
        //console.log(result)

        for(let b of result) {
            //console.log(b.constructor)
            //result[b['matchPeroid']].push(b);
            for(let key of Object.keys(b)) {
                //console.log('key:', key)
                //if(Number.isNaN(+key)) { continue; }
                //console.log('in')
                let match = b[key]
                switch(match) {
                    case '1H':
                        result['1H'].push(b);
                        //console.log(result)
                        break;
                    case '2H':
                        result['2H'].push(b);
                        //console.log(result)
                        break;
                    default:
                        console.log('error')
                }
            }

                //else { continue;}
                //delete b;
        //console.log(result)
        }
        //console.log(result)*/
        ctx.body=result
        //console.log(ctx.body)
        /**ctx.body = "TODO find the list of seasons of competition" + id;
        ctx.throw(500);*/
    })

    /**.get('/:playerid/events/duel', async (ctx, next)=>{
        const {playerid} = ctx.params;
        const {matchId, eventId} = ctx.query;
        // console.log(playerid, matchId, eventId)
        //const r = await eventCtl.retrieve(playerid);
        const r = await eventCtl.find({playerId:playerid, eventId, matchId});
        // console.log(r)
        
        let againstArray = [];

        r.map(
            element => {
                // console.log(element)   
                // console.log(element.duelAgainst)
                againstArray.push(element.duelAgainst)
            }
        )

        //let bisai = [];
        let result = [];
        for(let d of r) { result.push(d)}
        var dataSchema = mongoose.Schema({
            eventId:     { type: String },
            eventName:   { type: String },
            matchId: {type: String},
            playerId: {type: String},
            teamId: {type: String},
            duelAgainst: {type: String},
        });
        var dataItem = mongoose.model('result',dataSchema);
        //console.log(result)
        const data = dataItem.aggregate([
            {
                $group:{
                    _id:'$duelAgainst',
                    count:{$sum:1}
                }
            }
        ])
        /**for(let round of r) {
            console.log(round.constructor)
            for(let key of Object.keys(round)) {
                console.log('key:', key)
                //if(Number.isNaN(+key)) { continue; }
                //console.log('in')
                if(round[key] == matchId){
                    //for(let d of round) { bisai.push(d)}
                    bisai.push(round)
                    console.log(bisai)
                }
                else { continue;}
            }
        }
        for(let a of bisai) {
            //console.log(a.constructor)
            for(let key of Object.keys(a)) {
                //console.log('key:', key)
                //if(Number.isNaN(+key)) { continue; }
                //console.log('in')
                if(a[key] == 'Pass'){
                    //for(let d of round) { bisai.push(d)}
                    result.push(a)
                    console.log(result)
                }
                else { continue;}
            }
        }*/
        /**result['1H']=[];result['2H']=[];

        for(let b of result) {console.log(result)h(b);
            for(let key of Object.keys(b)) {
                console.log('key:', key)
                //if(Number.isNaN(+key)) { continue; }
                //console.log('in')
                let match = b[key]
                switch(match) {
                    case '1H':
                        result['1H'].push(b);
                        console.log(result)
                        break;
                    case '2H':
                        result['2H'].push(b);
                        console.log(result)
                        break;
                    default:
                        console.log('error')
                }
            }

                //else { continue;}
                //delete b;
        console.log(result)
        }
        ctx.body = data
        /**ctx.body = "TODO find the list of seasons of competition" + id;
        ctx.throw(500);*/
    //})

module.exports = router;

/**
 * @swagger
 * resourcePath: /api
 * description: All about API
 * definitions:
 *   matchplayer:
 *     type: "object"
 *     required:
 *       - "name"
 *     properties:
 *       matchId:
 *         type: "string"
 *       teamId:
 *         type: "string"
 *       playerId:
 *         type: "string"
 *       rate:
 *         type: "number"
 *       shot_rate:
 *         type: "number"
 *       pass_rate:
 *         type: "number"
 *       defending_rate:
 *         type: "number"
 *       skill_rate:
 *         type: "number"
 *       Actions:
 *         type: "object"
 *       Shots:
 *         type: "object"
 *       Passes:
 *         type: "object"
 *       Forward passes:
 *         type: "object"
 *       Lateral passes:
 *         type: "object"
 *       Back passes:
 *         type: "object"
 *       Smart passes:
 *         type: "object"
 *       Key passes:
 *         type: "object"
 */